package com.xhwl.data.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.dto.cent.sdata.devplatform.DeveloperDTO;
import com.xhwl.common.enums.AppBusinessTypeEnum;
import com.xhwl.common.enums.AppTypeEnum;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.App;
import com.xhwl.common.pojo.cent.sdata.Industry;
import com.xhwl.common.pojo.cent.sdata.devplatform.Developer;
import com.xhwl.common.query.cent.sdata.AppQuery;
import com.xhwl.common.query.cent.sdata.devplatform.DeveloperQuery;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.dao.IAppDao;
import com.xhwl.data.service.IAppService;
import com.xhwl.data.service.IIndustryService;
import com.xhwl.data.service.devplatform.IDeveloperService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author:
 * @create: 2020-11-25
 **/
@Service
public class AppServiceImpl extends ServiceImpl<IAppDao, App> implements IAppService {

    @Autowired
    private IAppDao appDao;

    @Autowired
    private IDeveloperService developerService;

    @Autowired
    private IIndustryService industryService;

    @Override
    public void create(App app) {
        paramCheck(app);
        if (null == app.getDevelopId()) {
            Developer developerDefault = developerService.getDefault();
            app.setDevelopId(developerDefault.getId());
        }
        appDao.insert(app);
    }

    @Override
    public void update(App app) {
        paramCheck(app);
        appDao.updateById(app);
    }

    private void paramCheck(App app) {
        if (null == app) {
            throw new DataException("参数错误");
        }
        if (null == app.getIndustryId()) {
            throw new DataException("参数错误，业态id为空");
        }
        if (null == app.getAppId()) {
            throw new DataException("参数错误，appId 为空");
        }
        if (null == app.getAppType()) {
            throw new DataException("参数错误，缺少应用类型");
        }
        if (StringUtils.isEmpty(app.getName())) {
            throw new DataException("参数错误，缺少应用名称");
        }
    }

    @Override
    public Page<App> findByPage(AppQuery appQuery, Page page) {
        Page pageResult = new Page();
        pageResult = appDao.selectPage(page, paramHandler(appQuery));
        List<App> records = pageResult.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            List<Integer> developIds = records.stream().map(App::getDevelopId).collect(Collectors.toList());
            DeveloperQuery developerQuery = new DeveloperQuery();
            developerQuery.setIds(developIds);
            List<DeveloperDTO> list = developerService.list(developerQuery);
            Map<Integer, List<DeveloperDTO>> developMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(list)) {
                developMap = list.stream().collect(Collectors.groupingBy(DeveloperDTO::getId));
            }
            List<Short> industryIds = records.stream().map(App::getIndustryId).collect(Collectors.toList());
            List<Industry> industries = industryService.listByIds(industryIds);
            Map<Integer, List<Industry>> industryMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(industries)) {
                industryMap = industries.stream().collect(Collectors.groupingBy(Industry::getId));
            }
            for (App app : records) {
                if (CollectionUtils.isNotEmpty(industryMap.get(app.getIndustryId().intValue()))) {
                    app.setIndustryName(industryMap.get(app.getIndustryId().intValue()).get(0).getName());
                }
                if (CollectionUtils.isNotEmpty(developMap.get(app.getDevelopId()))) {
                    app.setDevelopEntName(developMap.get(app.getDevelopId()).get(0).getEnterpriseName());
                }
                Short appType = app.getAppType().shortValue();
                List<AppBusinessTypeEnum> collect = AppBusinessTypeEnum.valuesOf(AppTypeEnum.valueOfId(appType)).stream().filter(i -> app.getBusinessType() != null && i.id == app.getBusinessType()).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collect)) {
                    app.setBusinessTypeName(collect.get(0).description);
                }
            }
        }
        return pageResult;
    }

    @Override
    public void delete(Integer id) {
        appDao.deleteById(id);
    }

    @Override
    public App getAppById(Integer id) {
        return appDao.selectById(id);
    }

    @Override
    public App getByAppId(String appId) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id", appId);
        return appDao.selectOne(queryWrapper);
    }

    @Override
    public List<App> list(AppQuery appQuery) {
        if (null == appQuery) {
            return Collections.emptyList();
        }
        return appDao.selectList(paramHandler(appQuery));
    }

    @Override
    public ResultJson getAppType() {
        AppTypeEnum[] values = AppTypeEnum.values();
        List<JSONObject> list = new ArrayList<>(values.length);
        for (AppTypeEnum value : values) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", value.type);
            jsonObject.put("value", value.description);
            list.add(jsonObject);
        }
        return ResultJson.success(list);
    }

    private QueryWrapper<App> paramHandler(AppQuery appQuery) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        if (null != appQuery.getIndustryId()) {
            Short industryId = appQuery.getIndustryId();
            queryWrapper.eq("industry_id", industryId);
        }
        if (!CollectionUtils.isEmpty(appQuery.getAppTypeCodes())) {
            queryWrapper.in("app_type", appQuery.getAppTypeCodes());
        }
        if (!CollectionUtils.isEmpty(appQuery.ids)) {
            queryWrapper.in("id", appQuery.ids);
        }
        if (!StringUtils.isEmpty(appQuery.appId)) {
            queryWrapper.eq("app_id", appQuery.appId);
        }
        if (!StringUtils.isEmpty(appQuery.keywords)) {
            queryWrapper.and(wrapper -> wrapper.like("name", appQuery.keywords).or().like("code", appQuery.keywords).or().in("app_id", appQuery.getKeywords()));
        }
        if (null != appQuery.appType) {
            queryWrapper.eq("app_type", appQuery.appType);
        }
        if (null != appQuery.getDevelopId()) {
            queryWrapper.eq("develop_id", appQuery.getDevelopId());
        }
        if (null != appQuery.getStatus()) {
            queryWrapper.eq("status", appQuery.getStatus());
        }
        if (CollectionUtils.isNotEmpty(appQuery.getIndustryIds())) {
            queryWrapper.in("industry_id", appQuery.getIndustryIds());
        }
        if (null != appQuery.getBusinessType()) {
            queryWrapper.eq("business_type", appQuery.getBusinessType());
        }
        return queryWrapper;
    }

    private QueryWrapper<App> paramHandler2(AppQuery appQuery, QueryWrapper<App> queryWrapper) {
        if (null != appQuery.getIndustryId()) {
            Short industryId = appQuery.getIndustryId();
            queryWrapper.eq("industry_id", industryId);
        }
        return queryWrapper;
    }

}
